#!/bin/bash

# ports to be checked, seperated by comma.
PORTS="{{PORTS}}"
# supported protocols, available values: all, tcp, udp.
PROTOCOL="{{PROTOCOL}}"

gen_result() {
  result=$1
  err_info=$2
  if [ "$result" == "success" ]; then
    echo "result: success"
  else
    echo "result: failed"
    echo "reason: $err_info"
  fi
  exit 0;
}

check_param() {
  protocol=$1
  if [ "$protocol" != "all" ] && [ "$protocol" != "tcp" ] && [ "$protocol" != "udp" ]; then
    gen_result "failed" "PROTOCOL $protocol is not valid."
  fi

  ports=$2
  IFS=',' read -ra arr <<< "$ports"
  for port in "${arr[@]}"; do
    [ -n "${port##*[!0-9]*}" ] || gen_result "failed" "port is not number."
  done
}

# check if port blocked for specific protocol.
is_port_blocked() {
  port=$1
  protocol=$2
  blocked='false'
  if [ "$protocol" == "all" ]; then
      if iptables -L -n -v | grep "$port" | head -1 | grep 'tcp\|udp' | grep "DROP" >/dev/null; then
        blocked='true'
      fi
  else
      if iptables -L -n -v | grep "$port" | head -1 | grep "$protocol" | grep "DROP" >/dev/null; then
        blocked='true'
      fi
  fi
  echo "$port: $blocked"
}

main() {
  check_param $PROTOCOL $PORTS

  echo "result: success"
  IFS=',' read -ra arr <<< "$PORTS"
  for port in "${arr[@]}"; do
    is_port_blocked "$port" $PROTOCOL
  done
}

main